<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * 支付类
 */

require '../vendor/autoload.php';

use Payment\ChargeContext;
use Payment\Config;
use Payment\Common\PayException;

date_default_timezone_set('Asia/Shanghai');

/**
 * 包含客户的配置文件
 * 本次 2.0 版本，主要的改变是将配置文件独立出来，便于客户多个账号的情况
 * 已经使用不同方式读取配置文件，如：db  file   cache等
 */
$aliconfig = require_once __DIR__ . '/config/aliconfig.php';
$wxconfig = require_once __DIR__ . '/config/wxconfig.php';

/**
 * 实例化支付环境类，进行支付创建
 */
$charge = new ChargeContext();

$type = $_REQUEST['type'];
try {
    if ($type == 'card') {
        $payData = getCardPayData();
    } elseif ($type == 'flow') {
        $payData = getFlowPayData();
       
    } elseif ($type == 'repay') {
        $payData = getRePayData();
    }
    if($payData['channel']==1){
           $charge->initCharge(Config::WX_CHANNEL_QR , $wxconfig);
          // 微信扫码支付，需要设置的参数
      $payData['product_id']  = '123456';
          $ret = $charge->charge($payData);
         
          $url = \Payment\Utils\DataParser::toQRimg($ret);
          echo json_encode(array('code_url'=>$url,'out_trade_no'=>$payData['order_no']));
    }else if($payData['channel']==2){
            $charge->initCharge(Config::ALI_CHANNEL_WAP , $aliconfig);
       $ret = $charge->charge($payData);
        header("Location:{$ret}");
    }
    
    
    
} catch (Exception $exc) {
    echo $exc->getMessage();
}

//获取流量支付数据
function getFlowPayData() {
    $rechargeItemId = $_REQUEST['rechargeItemId'];
    $phone =$_REQUEST['phone'];
    $payWay = $_REQUEST['payWay'];
    $res = file_get_contents("http://120.25.126.95:8033/cms/recharge/rechargeBase/create.do?rechargeItemId={$rechargeItemId}&phone={$phone}");
    if (empty($res)) {
        exit("网络错误");
    }
    $orderInfo = json_decode($res, true);
    $out_trade_no = $orderInfo['result']['orderNo'];
    // 订单信息
    $payData = [
        "order_no" => $out_trade_no,
        "amount" => $orderInfo['result']['price'] , // 单位为元 ,最小为0.01
        "client_ip" => '127.0.0.1',
        "subject" => $orderInfo['result']['title'],
        "body" => $orderInfo['result']['title'],
        "extra_param" => '',
        'channel'=> $payWay 
    ];
    return $payData;
}

//重新下单
function getRePayData() {
    session_start();
    $info = $_SESSION['submit-info'];
    $out_trade_no = $info['trade_no'];
    // 订单信息
    $payData = [
        "order_no" => $out_trade_no,
        "amount" => $info['card-count'] * $info['card-price'] + $info['card-express'], // 单位为元 ,最小为0.01
        "client_ip" => '127.0.0.1',
        "subject" => $info['card-title'],
        "body" => $info['card-title'],
        "extra_param" => '',
        'channel'=>$info['pay-way']
    ];
    return $payData;
}

//获取新卡支付数据
function getCardPayData() {
    //请求生成订单
    session_start();
    $info = isset($_SESSION['submit-info']) ? $_SESSION['submit-info'] : array();

    $payment = $info['selectPayWayIndex'] == 1 ? "tenPay" : "aliPay";
    $res = file_get_contents("http://120.25.126.95:8033/cms/shop/shopMifiCardOrder/create.do?platform=pc&payment={$payment}&shopMifiCardId={$info['cardItem']['id']}&count={$info['cardCount']}");
    //保存地址
    if (empty($res)) {
        echo json_encode(array('success' => false, 'message' => '网络错误'));
        exit;
    }
    $orderInfo = json_decode($res, true);
    if (empty($orderInfo['result'])) {
        echo json_encode(array('success' => false, 'message' => 'MIFI卡不存在'));
        exit;
    }

    $url = "http://120.25.126.95:8033/cms/shop/shopAddress/create.do?platform=pc&"
            . "provinceId={$info['address']['provinceId']}"
            . "&provinceName={$info['address']['provinceName']}"
            . "&cityId={$info['address']['cityId']}&"
            . "cityName={$info['address']['cityName']}&"
            . "townId={$info['address']['districtId']}&townName={$info['address']['districtName']}&address={$info['address']['street']}"
            . "&consignee={$info['address']['consignee']}&phone={$info['address']['phone']}&orderNo={$orderInfo['result']['orderNo']}";

    $res = file_get_contents($url);
    $res = json_decode($res, true);
    if (empty($orderInfo['result'])) {
        echo json_encode(array('success' => false, 'message' => '网络错误'));
        exit;
    }

    $out_trade_no = $orderInfo['result']['orderNo'];
    // 订单信息
    $payData = [
        "order_no" => $out_trade_no,
        "amount" => $orderInfo['result']['price'] , // 单位为元 ,最小为0.01
        "client_ip" => '127.0.0.1',
        "subject" => $orderInfo['result']['title'],
        "body" => $orderInfo['result']['title'],
        "extra_param" => '',
        'channel'=>$info['selectPayWayIndex']
    ];
    return $payData;
}
